﻿<template>
    <el-container>
        <el-header>
            <div class="left-panel">
                <el-button type="primary" plain icon="el-icon-plus" @click="opAdd">新增</el-button>
                <el-button type="primary" plain icon="el-icon-plus" @click="opUpdate">修改价格</el-button>
                <el-button type="warning" plain icon="el-icon-download" @click="opExport">导出数据</el-button>
                <!-- <el-button type="success" plain icon="el-icon-check" @click="opBatchPass">批量通过</el-button> -->
                <el-button type="danger" plain icon="el-icon-close" @click="opClose">终止</el-button>
            </div>
            <div class="right-panel">
                <el-button :icon="Search"   type="primary" @click="opBindData">查询</el-button>
                <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                <el-button text type="primary" @click="showCondition = !showCondition">
                    <span v-if="!showCondition">展开</span>
                    <span v-else>收起</span>
                    <vab-icon class="vab-dropdown" :class="{ 'vab-dropdown-active': fold }" icon="arrow-up-s-line" />
                </el-button>
            </div>
        </el-header>
        <el-foot v-show="showCondition">
            <vab-query-form-top-panel>
                <el-form inline label-width="49px" :model="queryForm" style="margin-top: 5px;margin-right: 20px;">
                    <el-row type="flex" style="flex-wrap:wrap">
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="申请编号" label-width="90px" style="width: 100%;">
                                <el-input placeholder="---请输入申请编号---" v-model="queryList.afterOrderCode" style="width: 100%;"/>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="申请单位" label-width="90px" style="width: 100%;"> 
                                <sc-auto-complete :orgType="2" :queryType="'store/search'" :placeholder="'---请输入申请单位---'" style="width: 100%;"
                                    v-model="queryList.storeName" @handleSelect="(e) => { this.queryList.storeName = e.storeName }"  />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="申请类型" label-width="90px" style="width: 100%;">
                                <el-select placeholder="---请选择申请类型---" v-model="queryList.afterOrderType" style="width: 100%;">
                                    <el-option label="---请选择---" value />
                                    <el-option v-for="item in optionsAfterOrderType" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="申请时间" label-width="90px" style="width: 100%;">
                                <el-date-picker style="width: 100%" v-model="queryList.dates" type="datetimerange"
                                    value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" range-separator="-"
                                    unlink-panels="true" start-placeholder="开始时间" end-placeholder="结束时间" :default-time="defaultTime"/>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="申请人" label-width="90px" style="width: 100%;">
                                <el-input placeholder="---请输入申请人---" v-model="queryList.createName" style="width: 100%;"/>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            
                            <el-form-item label="供应商" label-width="90px" style="width: 100%;"> 
                                <sc-auto-complete :orgType="3" :queryType="'supplier/search'" :placeholder="'---请输入供应商---'" style="width: 100%;"
                                    v-model="queryList.supplierName"
                                    @handleSelect="(e) => { this.queryList.supplierName = e.supplierName }"  />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="物料分类" label-width="90px" style="width: 100%;">
                                <el-tree-select placeholder="---请选择物料分类---" v-model="queryList.materialTypeIds"
                                    :props="{ label: 'label', value: 'value', children: 'children' }" :data="materialTypeTree"
                                    multiple :render-after-expand="false" show-checkbox style="width: 100%" />
                                </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            
                            <el-form-item label="物料简码" label-width="90px" style="width: 100%;">
                                <el-input placeholder="---请输入物料简码---" v-model="queryList.materialSimpCode" style="width: 100%;"
                                     />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="物料编码" label-width="90px" style="width: 100%;">
                                <el-input placeholder="---请输入物料编码---" v-model="queryList.materialCode"  style="width: 100%;"/>
                            </el-form-item>
                        </el-col>
                       
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="物料名称" label-width="90px" style="width: 100%;">
                                <el-input placeholder="---请输入物料名称---" v-model="queryList.materialName" style="width: 100%;"/>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
                            <el-form-item label="审核状态" label-width="90px" style="width: 100%;">
                                <el-select placeholder="---请选择状态---" v-model="queryList.status" style="width: 100%;">
                                    <el-option label="---请选择---" value />
                                    <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                       
                    </el-row>
                </el-form>
            </vab-query-form-top-panel>
        </el-foot>

        <el-main class="nopadding">
            <scTable ref="mytable" :queryType="'after-order/pages'" :data="listData" :queryList="queryList"
                :column="columnList" :orderList="OrderList" :sort-orders="['ascending', 'descending']"
                @selection-change="selectionChange" row-key="StoreId" key="StoreId" border show-summary remoteSummary
                @row-click="rowClick" :row-style="selectedStyle">
                <el-table-column type="selection" width="50" fixed="left"></el-table-column>
                <el-table-column label="序号" type="index" width="60" />
                <el-table-column prop="statusDesc" label="状态" width="120" sortable>
                    <template #default="scope">
                        <span style="color:#E6A23C;align-items: center;display: flex;"
                            v-if="scope.row.status == 0"><el-icon>
                                <WarnTriangleFilled />
                            </el-icon> {{ scope.row.statusDesc }}</span>
                        <span style="color:#67C23A;align-items: center;display: flex;"
                            v-else-if="scope.row.status == 1"><el-icon>
                                <CircleCheck />
                            </el-icon> {{ scope.row.statusDesc }}</span>
                        <span style="color:#F56C6C;align-items: center;display: flex;"
                            v-else-if="scope.row.status == 2"><el-icon>
                                <CircleClose />
                            </el-icon> {{ scope.row.statusDesc }}</span>
                        <span style="color:#F56C6C;align-items: center;display: flex;"
                            v-else-if="scope.row.status == 3"><el-icon>
                                <Back />
                            </el-icon> {{ scope.row.statusDesc }}</span>
                        <span style="color:#909399;align-items: center;display: flex;"
                            v-else-if="scope.row.status == 4"><el-icon>
                                <Lock />
                            </el-icon> {{ scope.row.statusDesc }}</span>
                        <span style="color:#F56C6C;align-items: center;display: flex;"
                            v-else-if="scope.row.status == 5"><el-icon>
                                <RefreshLeft />
                            </el-icon> {{ scope.row.statusDesc }}</span>
                        <span style="color:#909399;align-items: center;display: flex;"
                            v-else-if="scope.row.status == 6"><el-icon>
                                <Finished />
                            </el-icon> {{ scope.row.statusDesc }}</span>
                        <span v-else>{{ scope.row.statusDesc }}</span>

                    </template>
                </el-table-column>
                <el-table-column prop="afterOrderTime" label="申请时间" width="170" sortable></el-table-column>
                <el-table-column prop="storeName" label="申请单位" width="200" sortable></el-table-column>
                <el-table-column prop="afterOrderCode" label="申请编号" width="150" sortable></el-table-column>
                <el-table-column prop="materialNames" label="物料" width="250" height="120" sortable>

                    <template #default="scope">
                        <el-popover placement="bottom-start" :width="400" trigger="click">
                            <template #reference>
                                <div
                                    style="position: relative;text-overflow: ellipsis;white-space: nowrap;cursor: pointer;display: block;">
                                    <span v-for="item in scope.row.materialNames" :key="item">
                                        {{ item.materialName }};
                                    </span>
                                </div>
                            </template>
                            <div style="text-align: center;margin: 10px;font-size: 16px;font-weight: bold;">物料明细</div>
                            <el-table :data="scope.row.materialNames" style="width: 100%" stripe>
                                <el-table-column prop="rowNumber" label="序号" width="60" />
                                <el-table-column prop="materialImage" label="图片" width="60">

                                    <template #default="scope">
                                        <el-image style="width: 35px; height: 30px" :src="scope.row.materialImage" :fit="fit" @click="handlePreview(scope.row)"/>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="materialName" label="物料名称" />
                                <el-table-column prop="qty" label="数量" width="80" />
                            </el-table>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="totalQty" label="申请数量" width="100"></el-table-column>
                <el-table-column label="集采接单数量" width="150">

                    <template #default="scope">
                        <span v-if="scope.row.totalConfirmQty > 0">{{ scope.row.totalConfirmQty }}</span>
                        <span v-else>/</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="totalAmount" label="总额" width="100" sortable></el-table-column> -->
                <!-- <el-table-column prop="afterOrderTypes" label="申请类型" width="120" sortable show-overflow-tooltip></el-table-column> -->
                <el-table-column prop="supplierNames" label="供应商名称" width="120" sortable
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="createName" label="申请人" width="120" sortable></el-table-column>

                <el-table-column prop="remarks" label="申请备注" width="120" sortable></el-table-column>
                <el-table-column label="操作" width="200">

                    <template #default="scope">
                        <el-button-group>
                            <el-button text type="primary" size="small" @click="opShow(scope.row, scope.$index)"
                                v-if="scope.row.status == 1 || scope.row.status == 2 || scope.row.status == 3 || scope.row.status == 5">查看</el-button>
                            <el-button text type="primary" size="small" @click="opAudit(scope.row, scope.$index)"
                                v-if="scope.row.status == 0">审核</el-button>
                            <el-button text type="primary" size="small" @click="opEidt(scope.row, scope.$index)"
                                v-if="scope.row.status == 4">编辑</el-button>
                            <!-- <el-button text  type="primary" size="small" @click="opSend(scope.row, scope.$index)" v-if="scope.row.status==1">发货</el-button> -->
                            <el-popconfirm title="确定退回吗？" @confirm="opBack(scope.row, 3)" v-if="scope.row.status == 0">
                                <template #reference>
                                    <el-button text type="danger" size="small">退回</el-button>
                                </template>
                            </el-popconfirm>

                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>

    </el-container>

    <save-dialog v-if="dialogSave" ref="saveDialog" @fatherMethod="opBindData" @success="handleSaveSuccess"
        @closed="dialogSave = false"></save-dialog>
    <detail-dialog v-if="dialogDetail" ref="detailDialog" @fatherMethod="opBindData" @success="handleSaveSuccess"
        @closed="dialogDetail = false"></detail-dialog>
    <audit-dialog v-if="dialogAudit" ref="auditObj" @fatherMethod="opBindData" @success="handleSaveSuccess"
        @closed="dialogAudit = false"></audit-dialog>

        <detail-dialog v-if="uplogDetail" ref="upDialog" @fatherMethod="opBindData" @success="handleSaveSuccess"
        @closed="uplogDetail = false"></detail-dialog>

    <template>
        <el-dialog v-model="auditDialog" title="审核备注" :width="500" :center="true" append-to-body style="height: 480px">
            <el-row>
                <el-input v-model="auditRemarks" type="textarea" :rows="5" />
            </el-row>
            <template #footer>
                <el-button @click="auditDialog = false">取 消</el-button>
                <el-button type="primary" :loading="isSaveing" @click="setState">确定</el-button>
            </template>
        </el-dialog>
    </template>
     <!-- 预览组件 -->
     <el-image-viewer v-if="showImage" @close="closeViewer" :url-list="srcList" />
</template>

<script>
import saveDialog from "./save";
import detailDialog from "./detail";
import auditDialog from "./audit";
import upDialog from "./update";
import publicjs from "@/api/model/publicjs";
import tool from "@/utils/tool";
import config from "@/config";
export default {
    name: "afterListGroup",
    components: {
        saveDialog,
        detailDialog,
        auditDialog,
        publicjs,
        upDialog
    },
    data() {
        return {
            uplogDetail:false,
            dialogSave: false,
            dialogDetail: false,
            dialogAudit: false,
            //审核状态
            auditState: false,
            showCondition: false,
            selectionRows: [],
            pkList: ["StoreId"],
            columnList: [

            ],
            OrderList: { StoreId: "Asc" },
            queryList: {
            },
            result: "", // 运行结果
            props1: {
                checkStrictly: true,
                emitPath: false,
            },
            orgCodeList: "",
            orgNameList: "",
            addState: true, //可以增加
            editState: true, //可以修改
            editBatchState: true, //可以批量修改
            deleteState: true, //可以删除
            optionsStatus: [],//状态
            optionsAfterOrderType: [],//申请类型
            materialTypeTree: [],
            orgType: 1,
            activeRowIndex: null, // 存储被点击行的索引
             //预览图片
             previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            defaultTime:[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ]
        };
    },
    methods: {
        //添加
        opAdd() {
            this.dialogSave = true;
            this.$nextTick(() => {
                this.$refs.saveDialog.open("Add");
            });
        },
        //编辑
        opEidt(row) {
            this.dialogSave = true;
            this.$nextTick(() => {
                this.$refs.saveDialog.setData(row);
                this.$refs.saveDialog.open("Edit");
            });
        },
        opUpdate(){
            if (this.selectionRows.length == 0) {
                this.$message.error("请选择要操作的订单");
                return;
            }
            if (this.selectionRows.length > 1) {
                this.$message.error("只能选择一项进行操作！");
                return;
            }
            this.uplogDetail = true;
            console.log("this.selectionRows",this.selectionRows[0])
            this.$nextTick(() => {
                this.$refs.upDialog.setData(this.selectionRows[0]);
                this.$refs.upDialog.open("Updata");
            });
        },
        //查看
        opShow(row) {
            this.dialogDetail = true;
            this.$nextTick(() => {
                this.$refs.detailDialog.setData(row);
                this.$refs.detailDialog.open("Show");
            });
        },
        //审核
        opAudit(row) {
            this.dialogAudit = true;
            this.$nextTick(() => {
                this.$refs.auditObj.setData(row);
                this.$refs.auditObj.open("Show");
            });
        },
        //退回
        async opBack(row, status) {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post("after-order/state", { afterOrderId: row.afterOrderId, status: status, AuditRemarks: "" });
                if (returnValue.status == 200) {
                    this.$message.success("操作成功");
                    this.$refs.mytable.getData();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }

            } catch (error) {
                this.loading = false;
            }
        },
        async opClose(){
            console.log(1111111111)
            this.loading = true;
            if (this.selectionRows.length == 0) {
                this.$message.error("请选择要操作的订单");
                return;
            }

            if (this.selectionRows.length > 1) {
                this.$message.error("只能选择一项进行操作！");
                return;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post("after-order/close", { afterOrderId: this.selectionRows[0].afterOrderId});
                if (returnValue.status == 200) {
                    this.loading = false;
                    this.$message.success("操作成功");
                    this.$refs.mytable.getData();
                } else {
                    this.loading = false;
                    this.$message.error("操作失败:" + returnValue.msg);
                }

            } catch (error) {
                this.loading = false;
            }
        },
        //发货
        opSend() {

        },
        //导出
        async opExport() {
            try {
                if (this.selectionRows.length > 0) {
                    let arr = []
                    this.selectionRows.forEach(item => { arr.push(item.afterOrderId); });
                    await this.$API.auth.PostProcessApi.post(`after-order/export`,
                        { afterOrderIds: arr },
                        { responseType: 'blob' }
                    ).then((res) => {
                        this.downloadfile(res);
                    }).catch((err) => {
                        this.$message.error('下载错误：获取文件流错误')
                    });
                } else {
                    this.$message.error("请选择要导出的数据");
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //批量通过
        async opBatchPass() {
            try {

                if (this.selectionRows.length > 0) {
                    console.log("selectionRows", this.selectionRows);
                    let arr = [];
                    this.selectionRows.forEach(item => { arr.push(item.afterOrderId); });
                    console.log("批量通过", arr);

                    this.$API.auth.PostProcessApi.post("after-order/batch-state", { AfterOrderIds: arr, Status: 1 }).then((returnValue) => {
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$refs.mytable.getData();
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                        }
                    });

                } else {
                    this.$message.error("请选择要审核的数据");
                }

            } catch (error) {
                this.loading = false;
            }
        },
        //批量不通过
        async opBatchNoPass() {
            try {
                if (this.selectionRows.length > 0) {
                    console.log("selectionRows", this.selectionRows);
                    let arr = [];
                    this.selectionRows.forEach(item => { arr.push(item.afterOrderId); });
                    console.log("批量不通过", arr);
                    this.$API.auth.PostProcessApi.post("after-order/batch-state", { AfterOrderIds: arr, Status: 2 }).then((returnValue) => {
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$refs.mytable.getData();
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                        }
                    });

                }
                else {
                    this.$message.error("请选择要审核的数据");
                }

            } catch (error) {
                this.loading = false;
            }
        },
        //行点击
        rowClick(row, event, column) {
            console.log("行点击", row);
            this.activeRowIndex = row.afterOrderId;
        },
        //选中样式
        selectedStyle({ row, rowIndex }) {
            if (this.activeRowIndex === row.afterOrderId) {
                return { backgroundColor: '#87C4ED' };
            }
            return {};
        },
        downloadfile(blob) {
            console.log("res", blob)
            let fileReader = new FileReader()
            //var blob = new Blob([res], {type: 'application/octet-stream;charset=UTF-8'})
            fileReader.onload = function () {
                try {
                    var downloadElement = document.createElement('a')
                    var href = window.URL.createObjectURL(blob) // 创建下载的链接
                    downloadElement.style.display = 'none'
                    downloadElement.href = href
                    downloadElement.download = decodeURI("明细.xlsx") // 下载后文件名
                    document.body.appendChild(downloadElement)
                    downloadElement.click() // 点击下载
                    document.body.removeChild(downloadElement) // 下载完成移除元素
                    window.URL.revokeObjectURL(href)
                } catch (err) {
                    console.error("An error occurred during file download:", err);
                    this.$message.error("文件下载失败，请稍后重试。");
                }

            }
            fileReader.readAsText(blob)
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        //本地更新数据
        handleSaveSuccess(data, mode) {
            if (mode == "Add") {
                this.$refs.mytable.refresh();
            } else if (mode == "Edit") {
                this.$refs.mytable.refresh();
            }
        },
        async opBindData() {
            this.$refs.mytable.clearSort();
            this.$refs.mytable.getData();
        },
        resetSearch() {
            this.queryList = {};
        },
        async initOptions() {
            try {
                let  returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["AfterOrderStatus", "AfterOrderType"] }
                );
                if (returnValue.status == 200) {
                    console.log("returnValue", returnValue);
                    this.optionsStatus = returnValue.response.find(p => p.code == "AfterOrderStatus").optionsDetails;
                    this.optionsAfterOrderType = returnValue.response.find(p => p.code == "AfterOrderType").optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                let  returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
         //图片预览
         handlePreview(row) {
            console.log("materialImage",row.materialImage);
            if (!row.materialImage || row.materialImage.length == 0) {
                return;
            }
            this.previewUrl=[row.materialImage]; // 设置当前预览的图片 URL
            this.srcList=[row.materialImage]; // 设置预览列表
            this.showImage = true; // 显示 el-image

        },
        closeViewer(){
            this.showImage = false; 
        },


    },
    async mounted() {
        this.orgType = tool.data.get("USER_INFO").AccountType;
        var afterOrderCode = this.$route.query.afterOrderCode;
        if (afterOrderCode) {
            this.queryList.afterOrderCode = afterOrderCode
        }
        await this.initOptions();
        await this.opBindData();
    },
};
</script>
<style scoped>
/* .el-form-item {
    margin-bottom: 8px !important;
} */
</style>